package com.tanhua.app.interceptor;

import cn.hutool.http.HttpStatus;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyHandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头
        String token = request.getHeader("Authorization");
        boolean falg = JwtUtils.verifyToken(token);
        if (!falg){
       throw new RuntimeException("登录状态有误");

        }
        Claims claims = JwtUtils.getClaims(token);
        Long id =Long.parseLong(claims.get("id").toString());
      String mobile = claims.get("mobile").toString();
        User user = new User();
        user.setId(id);
        user.setMobile(mobile);
        UserThreadLocal.setThreadLocal(user);


        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       UserThreadLocal.remove();
    }
}
